package com.wss.util;

import org.apache.commons.io.FilenameUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * 文件上传工具类
 */
public class FileUploadUtil {

    /**
     * 图片上传方法
     * @param vcoverfile
     * @param request
     * @return
     * @throws IOException
     */
    public String uploadImage(MultipartFile vcoverfile, HttpServletRequest request) throws IOException {
        //使用UUID给图片重命名，并去掉四个“-”
        String fileName = UUID.randomUUID().toString().replaceAll("-", "");
        //获取文件的扩展名
        String ext = FilenameUtils.getExtension(vcoverfile.getOriginalFilename());
        //设置图片和视频的上传路径
        String vcoverurl = request.getSession().getServletContext().getRealPath("/WEB-INF/upload");
        System.out.println("vcoverurl:"+vcoverurl);
        fileName = fileName + "." + ext;
        File targetFile = new File(vcoverurl+"/"+fileName);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        //以绝对路径保存重名命后的图片
        vcoverfile.transferTo(targetFile);
        return "upload/"+fileName;
    }

    /**
     * 博客图片上传方法
     */
    public String uploadMkImage(MultipartFile mkimagefile, HttpServletRequest request) throws IOException {
        //使用UUID给图片重命名，并去掉四个“-”
        String fileName = UUID.randomUUID().toString().replaceAll("-", "");
        //获取文件的扩展名
        String ext = FilenameUtils.getExtension(mkimagefile.getOriginalFilename());
        //设置图片和视频的上传路径
        String mkImgUrl = request.getSession().getServletContext().getRealPath("/WEB-INF/mkimages");
        System.out.println("mkImgUrl:"+mkImgUrl);
        fileName = fileName + "." + ext;
        File targetFile = new File(mkImgUrl+"/"+fileName);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        //以绝对路径保存重名命后的图片
        mkimagefile.transferTo(targetFile);
        return "mkimages/"+fileName;
    }

    /**
     * 视频上传方法
     * @param videofile
     * @param request
     * @return
     * @throws IOException
     */
    public String uploadVideo(MultipartFile videofile, HttpServletRequest request) throws IOException {
        //获取视频的文件名
        String videofileName = videofile.getOriginalFilename();
        System.out.println(videofileName);
        //设置图片和视频的上传路径
        String vurl = request.getSession().getServletContext().getRealPath("/WEB-INF/videos");
        System.out.println("-videourl:"+vurl);
        File targetFile = new File(vurl+"/"+videofileName);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        //以绝对路径保存重名命后的图片
        videofile.transferTo(targetFile);
        return "videos/"+videofileName;
    }



}
